// 读取 VSCode API
const vscode = acquireVsCodeApi()
/////////////////////////////////////////////////////
// 定义一个处理函数，当界面的 JSON 变动时会调到这里
function OnAppJsonChanged(lvgl = {}) {
  lvgl = imageSizeHandler(lvgl);
  console.log("GET LVGL:", lvgl)
  for (let key in lvgl["schema"]){
    if (lvgl["schema"][key]["comType"] === "LvglImg" || lvgl["schema"][key]["comType"] === "LvglImgBtn"){

      if (lvgl["schema"][key]["comType"] === "LvglImg"){
        let localSrc = lvgl["schema"][key]["comConf"]["src"];
        if (lvgl["resources"][localSrc]){
          let natureVal = {};
          natureVal.width = lvgl["resources"][localSrc].width;
          natureVal.height = lvgl["resources"][localSrc].height;
          lvgl["schema"][key]["comConf"]["natureVal"] = natureVal;
        }
      }
    }
  }

  vscode.postMessage({
    command: "lvgl_json_receive",
    text: lvgl,
  });
}
/////////////////////////////////////////////////////
function LoadLvglDataFromWebviewState() {
  console.log("LoadLvglDataFromWebviewState")
  let lvgl = vscode.getState() || {}
  UpdateLvglMakerData(lvgl)
}
/////////////////////////////////////////////////////
async function UpdateLvglMakerData(lvgl = {}) {
  console.log("POLYFILL: UpdateLvglMakerData", lvgl)
  // 找到主控件
  let app = Ti.App.topInstance();
  let vm = app.$vm().findComBy(({ tiComType }) => "LvglMaker" == tiComType)
  if (vm) {
    console.log("得到主控件:", vm)
    console.log("设置到模型里 ...", lvgl)
    vm.notifyChange(lvgl)
  }
  // 警告一下
  else {
    console.warn("未取得主控件: LvglMaker")
  }
}
/////////////////////////////////////////////////////
// 设置事件监听，插件会初始化 JSON 数据
window.addEventListener('message', event => {
  let { command, text } = event.data;
  console.log("WebView: Listen message", { command, text })
  if (!command) {
    // console.log('---------------------------message：aaaa');
    return;
  }
  console.log("========", command);
  switch (command) {
    //示例文件
    case 'lvgl':
      let lvgl = text;
      console.log('Webview 接受到LVGL对象:', lvgl);
      // 首先存一份状态
      vscode.setState(lvgl);
      UpdateLvglMakerData(lvgl);
      break;
    case 'lvglPictureBase64':
      console.log(text)
      if (text.readBase64) {
        console.log('Webview 接受到BASE64内容:', text.pictureBase64Path, text.base64.substring(0, 100), "...");
        let fnList = IMG_BASE64_CALLBACKS[text.pictureBase64Path];
        if(fnList && fnList.length > 0) {
          for(let fn of fnList) {
            fn(text.base64);
          }
        }
        delete IMG_BASE64_CALLBACKS[text.pictureBase64Path]
      }
      break;
    case 'uiConvert':
      const uiJsonObj = text[0];
      const uiHandleData = text[1];
      const uiLuaDataType = text[2];
      let uiConvertedObj = transcoderInitialization(uiLuaDataType,uiJsonObj,uiHandleData)
      vscode.postMessage({
        'command':'uiConvertOutputData',
        'text':uiConvertedObj
      })
      break;
  }
});
/////////////////////////////////////////////////////
// 界面初始化完成
function notifyPageReady() {
  console.log("WebView: notifyPageReady")
  vscode.postMessage({
    command: "lvglPageReady",
    text: true
  });
}
/////////////////////////////////////////////////////
// 这里存储控件加载的文件内容
var IMG_BASE64_CALLBACKS = {
  /* src: [function(base64Src) ... ] */
}
/////////////////////////////////////////////////////
function vscodeEvalLocalImgSrc(src, callback) {
  console.log(`------------> 请求读取图片 : ${src}`);
  let fnList = IMG_BASE64_CALLBACKS[src]
  let firstCall = false
  if (!fnList) {
    fnList = []
    IMG_BASE64_CALLBACKS[src] = fnList
    firstCall = true
  }
  fnList.push(callback)

  if (firstCall) {
    vscode.postMessage({
      'command': 'lvglReadBase64',
      "text": src
    });
  }
}

// 临时处理图片真实宽高嵌入json中
function imageSizeHandler(lvgl) {
  for (let key in lvgl["schema"]) {
    if (lvgl["schema"][key]["comType"] === "LvglImg" || lvgl["schema"][key]["comType"] === "LvglImgBtn") {
      let localSrc = lvgl["schema"][key]["comConf"]["src"];
      if (localSrc){
        if (lvgl["schema"][key]["comType"] === "LvglImg") {
          if (lvgl["resources"][localSrc]) {
            let natureVal = {};
            natureVal.width = lvgl["resources"][localSrc].width;
            natureVal.height = lvgl["resources"][localSrc].height;
            lvgl["schema"][key]["comConf"]["natureVal"] = natureVal;
          }
        } else {
          // let natureVal = {};
          // for (let val in localSrc) {
          //   natureVal[val] = {}
          //   let curKey = localSrc[val];
          //   if (lvgl["resources"][curKey]) {
          //     natureVal[val].width = lvgl["resources"][curKey].width;
          //     natureVal[val].height = lvgl["resources"][curKey].height;
          //   } else {
          //     break;
          //   }
          // }
          // lvgl["schema"][key]["comConf"]["natureVal"] = natureVal;
        }
      }
    }
  }
  return lvgl;
}


